import AudioPlayer from '@/components/AudioPlayer';
import { Empty, Form, Tabs } from 'antd';
import { completeImgUrl, getFilenameByKey } from 'common/utils/utils';
import { memo, useEffect, useMemo, useState } from 'react';

const AudioItem = () => {
  const filters = Form.useWatch('filters');
  const files = Form.useWatch('files') as string[] | undefined;
  const presetFiles = Form.useWatch('presetFiles') as string[] | undefined;

  const allFiles = useMemo(() => {
    return [...(files || []), ...(presetFiles || [])];
  }, [files, presetFiles]);

  const eqs = useMemo(() => {
    return filters?.eqs || [];
  }, [filters]);

  const [activeKey, setActiveKey] = useState<string>();

  useEffect(()=>{
    if(allFiles.length){
      if(allFiles.every(item=>item !== activeKey)){
        setActiveKey(allFiles[0])
      }
    }else{
      setActiveKey(undefined);
    }
  },[allFiles]);

  const items = useMemo(() => {
    return allFiles.map((item) => {
      return {
        key: item,
        label: getFilenameByKey(item),
        children: (
          <AudioPlayer
            src={completeImgUrl(item)!}
            eqs={eqs}
            isActive={activeKey === item}
          />
        ),
      };
    });
  }, [files, presetFiles, eqs, activeKey]);


  if (items.length === 0) {
    return <Empty description="请先添加试听音频" />;
  }

  return (
    <Tabs items={items} activeKey={activeKey} onChange={setActiveKey}></Tabs>
  );
};

export default memo(AudioItem);
